package com.huiztech.kaoqinji;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKOLUpdateElement;
import com.baidu.mapapi.map.MKOfflineMap;
import com.baidu.mapapi.map.MKOfflineMapListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.MyLocationOverlay.LocationMode;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.huiztech.util.BMapUtil;

public class FootprintActivity extends BaseActivity {
    // 定位相关
    LocationClient mLocClient;
    LocationData locData = null;
    public MyLocationListenner myListener = new MyLocationListenner();

    // 定位图层
    locationOverlay myLocationOverlay = null;
    MyAddressOverlay myAddressOverlay = null;
    // 弹出泡泡图层
    // private PopupOverlay pop = null;// 弹出泡泡图层，浏览节点时使用
    public TextView popupText = null;// 泡泡view
    private View viewCache = null;

    // 地图相关，使用继承MapView的MyLocationMapView目的是重写touch事件实现泡泡处理
    // 如果不处理touch事件，则无需继承，直接使用MapView即可
    MyLocationMapView mMapView = null; // 地图View
    private MapController mMapController = null;
    MKOfflineMap mOffline = null; //离线地图 申明变量

    // UI相关
    OnCheckedChangeListener radioButtonListener = null;
    Button requestLocButton = null;

    boolean isRequest = false;// 是否手动触发请求定位
    boolean isFirstLoc = true;// 是否首次定位

    private LinearLayout backLayout, historyLayout;
    private LocApplication locApplication;

    View merchantLoadImage = null;
    PopupOverlay pop = null;// 弹出泡泡图层，点击图标使用
    static GeoPoint pt;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locApplication = (LocApplication) getApplication();
        ((LocApplication) getApplication()).mBMapManager.start();
        setContentView(R.layout.activity_footprint);
        findView();
        backLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        historyLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.i("HistoryBtn", "nothing");
            }
        });

        //离线地图初始化
        mOffline = new MKOfflineMap();
        //offline 实始化方法用更改。
        mOffline.init(mMapController, new MKOfflineMapListener() {
            @Override
            public void onGetOfflineMapState(int type, int state) {
                switch (type) {
                case MKOfflineMap.TYPE_DOWNLOAD_UPDATE: {
                    MKOLUpdateElement update = mOffline.getUpdateInfo(state);
                    //mText.setText(String.format("%s : %d%%", update.cityName, update.ratio));
                }
                    break;
                case MKOfflineMap.TYPE_NEW_OFFLINE:
                    Log.d("OfflineDemo", String.format("add offlinemap num:%d", state));
                    break;
                case MKOfflineMap.TYPE_VER_UPDATE:
                    Log.d("OfflineDemo", String.format("new offlinemap ver"));
                    break;
                }
            }
        });

        // 地图初始化
        mMapView = (MyLocationMapView) findViewById(R.id.bmapsView);
        mMapController = mMapView.getController();
        mMapView.getController().setZoom(17);
        mMapView.getController().enableClick(true);
        mMapView.setBuiltInZoomControls(true);
        // 创建 弹出泡泡图层
        createPaopao();

        // 定位初始化
        mLocClient = new LocationClient(this);
        locData = new LocationData();
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(locApplication.getAcquisition_interval());
        mLocClient.setLocOption(option);
        mLocClient.start();

        // 定位图层初始化
        myLocationOverlay = new locationOverlay(mMapView);
        myLocationOverlay.setMarker(getResources().getDrawable(R.drawable.icon_geo));
        // 设置定位数据
        myLocationOverlay.setData(locData);
        // 添加定位图层
        mMapView.getOverlays().add(myLocationOverlay);
        myLocationOverlay.enableCompass();
        // 修改定位数据后刷新图层生效
        mMapView.refresh();
        //mMapView.onTouchEvent();
        //        mMapView.setOnTouchListener(new OnTouchListener() {
        //
        //            @Override
        //            public boolean onTouch(View v, MotionEvent event) {
        //                switch (event.getAction()) {
        //                case MotionEvent.ACTION_MOVE:
        //                    LogUtils.i( MotionEvent.ACTION_MOVE+"++");
        //                    return true;
        //                default:
        //                    LogUtils.i(event.getAction()+"==");
        //                    int x = (int) event.getX();
        //                    int y = (int) event.getY();
        //                    //将像素坐标转为地址坐标
        //                    GeoPoint pt = mMapView.getProjection().fromPixels(x, y);
        //                    LogUtils.i(pt.getLatitudeE6() + "==" + pt.getLongitudeE6());
        //                    //生成ItemizedOverlay图层用来标注结果点
        //
        //                    return true;
        //                }
        //            }
        //        });

    }

    public  void setAddressOverlay(GeoPoint pt) {
        ItemizedOverlay<OverlayItem> itemOverlay = new ItemizedOverlay<OverlayItem>(null, mMapView);
        //生成Item
        OverlayItem item = new OverlayItem(pt, "", null);
        //得到需要标在地图上的资源
        Drawable marker = getResources().getDrawable(R.drawable.icon_gcoding);
        //为maker定义位置和边界
        marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());
        //给item设置marker
        item.setMarker(marker);
        //在图层上添加item
        itemOverlay.addItem(item);
        //清除地图其他图层
        mMapView.getOverlays().clear();
        //添加一个标注ItemizedOverlay图层
        mMapView.getOverlays().add(itemOverlay);
        //执行刷新使生效
        mMapView.refresh();
    }

    /**
     * 手动触发一次定位请求
     */
    public void requestLocClick() {
        isRequest = true;
        mLocClient.requestLocation();
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) return;
            locData.latitude = location.getLatitude();
            locData.longitude = location.getLongitude();
            locData.accuracy = location.getRadius();
            locData.direction = location.getDerect();

            // 更新定位数据
            myLocationOverlay.setData(locData);
            mMapView.refresh();
            // 更新图层数据执行刷新后生效
            if (isRequest || isFirstLoc) {
                mMapController.animateTo(new GeoPoint((int) (locData.latitude * 1e6), (int) (locData.longitude * 1e6)));
                myLocationOverlay.setLocationMode(LocationMode.FOLLOWING);
                isRequest = false;
            }
            // 首次定位完成
            isFirstLoc = false;
        }

        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null) {
                return;
            }
        }
    }

    // 继承MyLocationOverlay重写dispatchTap实现点击处理
    public class locationOverlay extends MyLocationOverlay {

        public locationOverlay(MapView mapView) {
            super(mapView);
        }

        @Override
        protected boolean dispatchTap() {
            // 处理点击事件,弹出泡泡
            popupText.setBackgroundResource(R.drawable.popup);
            popupText.setText(controller.getInfoByLocal(AppConst.SP_MAP_POP_TEXT, "我在这里..."));
            pop.showPopup(BMapUtil.getBitmapFromView(popupText), new GeoPoint((int) (locData.latitude * 1e6),
                    (int) (locData.longitude * 1e6)), 8);
            return true;
        }

    }

    public class MyAddressOverlay extends ItemizedOverlay<OverlayItem> {
        public MyAddressOverlay(Drawable arg0, MapView arg1) {
            super(arg0, arg1);
        }

        //        @Override
        //        public boolean onTap(int index) {
        //            try {
        //                OverlayItem item = getItem(index);
        //                mCurItem = item;
        //                String[] strarray = mCurItem.getSnippet().split(":");
        //                merchantName.setText(strarray[0]);
        //                imageLoader.displayImage(AppConst.BASE_IMAGE + strarray[1], merchantIcon, options);
        //                Bitmap[] bitMaps = { BitmapUtil.getBitmapFromView(merchantLoadImage),
        //                        };
        //
        //                pop.showPopup(bitMaps, item.getPoint(), 32);
        //                Log.e("point", item.getPoint() + "");
        //            } catch (Exception e) {
        //                e.fillInStackTrace();
        //            }

        @Override
        protected boolean onTap(int arg0) {
            popupText.setBackgroundResource(R.drawable.popup);
            popupText.setText(controller.getInfoByLocal(AppConst.SP_MAP_POP_TEXT, "我在这里..."));
            pop.showPopup(BMapUtil.getBitmapFromView(popupText), new GeoPoint((int) (locData.latitude * 1e6),
                    (int) (locData.longitude * 1e6)), 8);
            return true;

        }

    }

    /**
     * 创建弹出泡泡图层
     */
    public void createPaopao() {
        viewCache = getLayoutInflater().inflate(R.layout.custom_text_view, null);

        popupText = (TextView) viewCache.findViewById(R.id.textcache);
        // 泡泡点击响应回调
        PopupClickListener popListener = new PopupClickListener() {
            @Override
            public void onClickedPopup(int index) {
                Log.v("click", "clickapoapo");
            }
        };
        pop = new PopupOverlay(mMapView, popListener);
        //  MyLocationMapView.pop = pop;
    }

    private void findView() {
        backLayout = (LinearLayout) findViewById(R.id.footprint_back_layout);
        historyLayout = (LinearLayout) findViewById(R.id.footprint_history_layout);
    }

    // ==============================================================

    @Override
    protected void onPause() {
        mMapView.onPause();
        //        if (bMapManager != null) {
        //            bMapManager.getLocationManager().removeUpdates(mLocationListener);
        //            bMapManager.stop();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        if (mLocClient != null) mLocClient.stop();
        mMapView.destroy();
        ((LocApplication) getApplication()).mBMapManager.stop();
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mMapView.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

//   static class MyLocationMapView extends MapView {
//        PopupOverlay pop;
//        Context context;
//
//        public MyLocationMapView(Context context) {
//            super(context);
//            this.context = context;
//        }
//
//        public MyLocationMapView(Context context, AttributeSet attrs) {
//            super(context, attrs);
//        }
//
//        public MyLocationMapView(Context context, AttributeSet attrs, int defStyle) {
//            super(context, attrs, defStyle);
//        }
//
//        @Override
//        public boolean onTouchEvent(MotionEvent event) {
//            int x = (int) event.getX();
//            int y = (int) event.getY();
//            //将像素坐标转为地址坐标
//            pt = this.getProjection().fromPixels(x, y);
//          //setAddressOverlay(pt);
//            if (!super.onTouchEvent(event)) {
//                // 消隐泡泡
//                if (pop != null && event.getAction() == MotionEvent.ACTION_UP) pop.hidePop();
//            }
//            //Toast.makeText(context, pt.getLatitudeE6()+"=="+pt.getLongitudeE6(), Toast.LENGTH_SHORT).show();
//            return super.onTouchEvent(event);
//
//            //  return true;
//        }
//        //
//    }

}

// // 定位初始化
// locData = new LocationData();
// mLocClient = new LocationClient(this);
// mLocClient.registerLocationListener(myListener);
// setOption();
//
// mMapView = (MyLocationMapView) findViewById(R.id.bmapsView);// 地图初始化
// setMapController(); // 设置地图控制器
// createPaopao();// 创建 弹出泡泡图层
//
// myLocationOverlay = new locationOverlay(mMapView);// 定位图层初始化
// myLocationOverlay.setData(locData);
// mMapView.getOverlays().add(myLocationOverlay);// 添加定位图层
// myLocationOverlay.enableCompass();
// mMapView.refresh();// 修改定位数据后刷新图层生效

//
// private void setMapController() {
// mMapController = mMapView.getController();
// mMapView.getController().setZoom(17);
// mMapView.getController().enableClick(true);
// mMapView.setBuiltInZoomControls(true);
// }
//
// private void setOption() {
// LocationClientOption option = new LocationClientOption();
// option.setOpenGps(true);// 打开gps
// option.setCoorType("bd09ll"); // 设置坐标类型
// option.setAddrType("all");
// option.setScanSpan(5000);
// option.setServiceName("com.baidu.location.service_v2.9");
// mLocClient.setLocOption(option);
// mLocClient.start();
// }

